package com.jameci.luntan.controller;

import com.jameci.luntan.dto.AccessTokenDTO;
import com.jameci.luntan.dto.GithubUserDTO;
import com.jameci.luntan.mapper.UserMapper;
import com.jameci.luntan.model.User;
import com.jameci.luntan.model.UserExample;
import com.jameci.luntan.provider.GithubProvider;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
public class AuthorizeController {
    @Autowired
    private GithubProvider githubProvider;
    @Autowired
    private UserMapper userMapper;
    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${github.redirect.uri}")
    private String redirectUri;
    @GetMapping("/callback")
    public String callback(
            @RequestParam(name="code") String code,
            @RequestParam(name="state") String state,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        accessTokenDTO.setState(state);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        String accessToken = githubProvider.getAccessToken(accessTokenDTO);
        GithubUserDTO githubUserDTO = githubProvider.getUser(accessToken);
        if(githubUserDTO.getLogin() != null) {
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(githubUserDTO.getLogin());
            user.setAccountId(String.valueOf(githubUserDTO.getId()));
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModified(user.getGmtCreate());
            user.setBio(githubUserDTO.getBio());
            System.out.println(githubUserDTO.toString());
            user.setAvatarUrl(githubUserDTO.getAvatar_url());
            UserExample userExample = new UserExample();
            userExample.createCriteria().andAccountIdEqualTo(user.getAccountId());
            List<User> userInDatabases = userMapper.selectByExample(userExample);
            if(userInDatabases.size() == 0) userMapper.insert(user);
            else {
                User userInDatabase = userInDatabases.get(0);
                user.setId(userInDatabase.getId());
                user.setGmtCreate(userInDatabase.getGmtCreate());
                UserExample userExample1 = new UserExample();
                userExample1.createCriteria().andIdEqualTo(user.getId());
                userMapper.updateByExample(user, userExample1);
            }
            response.addCookie(new Cookie("token", token));
            //登录成功，写cookie，写session
            request.getSession().setAttribute("user", user);
            System.out.println("登录成功");
            return "redirect:index";
        } else {
            System.out.println("登录失败");
            //登录失败，重新登录
            return "redirect:index";
        }
    }
}
